package logic

import (
	"context"
	"fmt"
	"github.com/gorilla/websocket"
	"io"
	"os"
	"time"

	"yunzhan/log-server/internal/svc"
	"yunzhan/log-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LogLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LogLogic {
	return &LogLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LogLogic) Log(req *types.WebSocketRequest, conn *websocket.Conn) error {
	logFile := "F:\\project\\yunzhan\\logs\\" + req.LogFile
	file, err := os.OpenFile(logFile, os.O_RDONLY|os.O_APPEND, 0)
	if err != nil {
		return conn.WriteMessage(websocket.TextMessage, []byte("Could not open log file"))
	}

	logx.Infof("读取日志文件: %s", logFile)
	defer file.Close()

	// 第一次读取整个日志文件
	buf := make([]byte, 1024)
	for {
		n, err := file.Read(buf)
		if err != nil {
			if err == io.EOF {
				break // 文件读取结束
			}
			return conn.WriteMessage(websocket.TextMessage, []byte("Error reading log file"))
		}
		fmt.Println("日志文件内容: ", string(buf[:n]))
		if n > 0 {
			err = conn.WriteMessage(websocket.TextMessage, buf[:n])
			if err != nil {
				return err // 发送失败
			}
		}
	}

	// 设置文件指针到文件末尾
	file.Seek(0, io.SeekEnd)

	// 每隔一段时间读取日志文件
	for {
		buf := make([]byte, 1024)
		n, err := file.Read(buf)
		if err != nil {
			if err == io.EOF {
				time.Sleep(1 * time.Second) // 文件读取结束，等待1秒
				continue
			}
			return conn.WriteMessage(websocket.TextMessage, []byte("Error reading log file"))
		}
		fmt.Println("日志文件内容: ", string(buf[:n]))
		if n > 0 {
			err = conn.WriteMessage(websocket.TextMessage, buf[:n])
			if err != nil {
				return err // 发送失败
			}
		}
	}

}
